package cn.topcodes.tcsf.cms.service;

import cn.topcode.unicorn.utils.StringUtil;
import cn.topcodes.tcsf.cms.domain.entity.ArticleLabel;
import cn.topcodes.tcsf.admin.commons.generic.GenericService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章标签表 服务
 *
 * @author Yvan
 * @date 2018-02-08 17:45:21
 */
@Service
public class ArticleLabelService extends GenericService<ArticleLabel> {


    /**
     * 新增
     *
     * @param labels
     * @return
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public String createLabel(String labels) {
        List<Long> labelIds = new ArrayList<>();
        if (StringUtil.isNotBlank(labels)) {
            String[] split = labels.split(",");
            for (String s : split) {
                if (StringUtil.isNotBlank(s)) {
                    Example example = this.buildExample();
                    example.or().andEqualTo(ArticleLabel.FIELD_NAME, s);
                    ArticleLabel articleLabel = this.findOne(example);
                    if (null == articleLabel) {
                        articleLabel = new ArticleLabel();
                        articleLabel.setName(s);
                        this.create(articleLabel);
                    }
                    labelIds.add(articleLabel.getId());
                }
            }
        }
        return StringUtils.join(labelIds, ",");
    }

    public List<String> findByIds(String ids) {
        List<String> labelNames = new ArrayList<>();
        if (StringUtils.isNotBlank(ids)) {
            String[] split = ids.split(",");
            for (String s : split) {
                if (StringUtils.isNotBlank(s)) {
                    ArticleLabel articleLabel = this.findOne(Long.parseLong(s));
                    if (null != articleLabel) {
                        labelNames.add(articleLabel.getName());
                    }
                }
            }
        }
        return labelNames;
    }
}
